#include "StdAfx.h"
#include "RadaParam.h"
#include "RadaRaramDlg.h"

auto_ptr<CRadaParam> CRadaParam::s_StaticParam;
CCriticalSection	 CRadaParam::s_cs;
int					 CRadaParam::s_count = 0;

CRadaParam::CRadaParam(LPCTSTR stzFileName)
{
	using namespace boost::property_tree;
	tptree pt;

	try
	{
		tifstream in(stzFileName);

		xml_parser::read_xml(in, pt);
		m_NV = 3;
		m_NCLASS = pt.get(_T("Param.rada.NCLASS"), -2);
		m_NOR = pt.get(_T("Param.rada.m_NOR"), 11);
		m_NI = pt.get(_T("Param.rada.NI"), 2);
		m_LL = pt.get(_T("Param.rada.LL"), 9);
		m_XL = pt.get<float>(_T("Param.rada.XL"), (float)1.0e-9);

		m_dIntegrationStep = pt.get<double>(_T("Param.rada.Step"), 10.0);
	}
	catch(xml_parser_error &e)
	{
		throw CCustomException(_T("line %d file %s:\n%s"), e.line(), e.filename().c_str(), e.message().c_str());
	}
	catch (const ptree_bad_data& error)
	{
		throw CCustomException(_T("ptree_bad_data: %s"), error.what());
	}
	catch (const ptree_bad_path& error)
	{
		throw CCustomException(_T("ptree_bad_path: %s"), error.what());
	}
	catch(...)
	{
		throw CCustomException(_T("Unknown error"));
	}
	++s_count;
}

CRadaParam::CRadaParam(void)
: m_NV(0)
, m_NCLASS(0)
, m_NOR(0)
, m_NI(0)
, m_LL(0)  
, m_XL(0.0)
, m_dIntegrationStep(0.0)
{
	CAutoCriticalSection acs(s_cs);
	if(s_StaticParam.get() == NULL)
	{
		LPCTSTR stzConfigFile = GetFileName();
		if(stzConfigFile == NULL || stzConfigFile[0] == 0)
			throw CCustomException(_T("CRadaParam::CRadaParam: empty config file name"));

		s_StaticParam = auto_ptr<CRadaParam>(new CRadaParam(stzConfigFile));
	}
	*this = *s_StaticParam;
	++s_count;
}

CRadaParam::~CRadaParam(void)
{
	--s_count;
	if(s_count == 1) // only static still destroy it
	{
		s_StaticParam.reset();
	}

	if(s_StaticParam.get() == this) // this is last? should store settings
	{
		CStdString strError;
		using namespace boost::property_tree;
		tptree pt;

		try
		{
			tifstream in(GetFileName());
			xml_parser::read_xml(in, pt);

			pt.put(_T("Param.rada.NCLASS"), m_NCLASS);
			pt.put(_T("Param.rada.m_NOR"), m_NOR);
			pt.put(_T("Param.rada.NI"), m_NI);
			pt.put(_T("Param.rada.LL"), m_LL);
			pt.put(_T("Param.rada.XL"), m_XL);

			pt.put(_T("Param.rada.Step"), m_dIntegrationStep);
			in.close();

			tofstream out(GetFileName());
			xml_parser::write_xml(out, pt);
		}
		catch(xml_parser_error &e)
		{
			throw CCustomException(_T("line %d file %s:\n%s"), e.line(), e.filename().c_str(), e.message().c_str());
		}
		catch(...)
		{
			strError = _T("Unknown error");
		}

		if(strError.length())
		{
			strError.Format(_T("Error storing rada param: %s"), strError.c_str());
			AfxMessageBox(strError);
		}
	}
}

bool CRadaParam::ShowSettings()
{
	CRadaParam tmp;
	CAutoCriticalSection acs(s_cs);
	CRadaRaramDlg dlg(&tmp);

	if(dlg.DoModal() == IDOK)
		*s_StaticParam = tmp;
	return true;
}